//
//  GKZYUserCenterViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYUserCenterViewController.h"

@interface GKZYUserCenterViewController ()

@end

@implementation GKZYUserCenterViewController

- (void)viewWillAppear:(BOOL)animated
{
    [self.tableViewList reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用户中心";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.arrayList = [NSMutableArray arrayWithObjects:@"修改资料",@"重置密码",@"意见反馈",@"关于我们", nil];
    self.arrayImage = [NSMutableArray arrayWithObjects:@"UserCenter_Edit",@"UserCenter_Password",@"UserCenter_Advise",@"UserCenter_AboutUs", nil];
    
    self.tableViewList = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    self.tableViewList.delegate = self;
    self.tableViewList.dataSource = self;
    [self.view addSubview:self.tableViewList];
    self.tableViewList.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] init];
    [leftBarButton setTitle:@""];
    leftBarButton.enabled = NO;
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

- (NSMutableArray *)arrayList
{
    if (!_arrayList) {
        _arrayList = [[NSMutableArray alloc] init];
    }
    return _arrayList;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayList.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if ([AVUser currentUser].username || [UserMessageShare sharedUserMessage].currentWeChatUserName) {
            static NSString *cell_login = @"cell_login";
            GKZYUserLoginTableViewCell *loginCell = [tableView dequeueReusableCellWithIdentifier:cell_login];
            if (!loginCell) {
                loginCell = [[GKZYUserLoginTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_login];
            }
            if ([AVUser currentUser].username) {
                [self addLoginCellContentOnCell:loginCell];
            }else if([UserMessageShare sharedUserMessage].currentWeChatUserName){
                loginCell.labelUserName.text = [UserMessageShare sharedUserMessage].currentWeChatUserName;
                [loginCell.imageHeadPortrait sd_setImageWithURL:[NSURL URLWithString:[UserMessageShare sharedUserMessage].currentWeChatUserIcon]];
            }
            self.rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
            self.navigationItem.rightBarButtonItem = self.rightBarButton;
            return loginCell;
        }else if (![AVUser currentUser].username || ![UserMessageShare sharedUserMessage].currentWeChatUserName){
            static NSString *cell_logout = @"cell_logout";
            GKZYUserLogoutTableViewCell *logoutCell = [tableView dequeueReusableCellWithIdentifier:cell_logout];
            if (!logoutCell) {
                logoutCell = [[GKZYUserLogoutTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_logout];
            }
            [self addLogoutCellOnCell:logoutCell];
            return logoutCell;
        }
    }else{
        static NSString *cell_id = @"cell_id";
        GKZYUserCenterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
        if (cell == nil) {
            cell = [[GKZYUserCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_id];
        }
        
        NSString *labelContent = self.arrayList[indexPath.row - 1];
        NSString *imageName = self.arrayImage[indexPath.row - 1];
        
        cell.labelContent.text = labelContent;
        cell.imageViewIcon.image = [UIImage imageNamed:imageName];
        return cell;
    }
    return nil;
}

- (void)addLoginCellContentOnCell:(GKZYUserLoginTableViewCell *)loginCell
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInformation"];
    [query whereKey:@"userName" equalTo:[AVUser currentUser].username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        AVObject *object = [objects firstObject];
        self.userObjectId = object.objectId;
        self.userObject = object;
        AVFile *userImage = [object[@"localData"] objectForKey:@"userImage"];
        if (userImage) {
            [userImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                if (data) {
                    if (self.userIcon.image) {
                        loginCell.imageHeadPortrait.image = self.userIcon.image;
                    }else{
                        loginCell.imageHeadPortrait.image = [UIImage imageWithData:data];
                    }
                    loginCell.imageHeadPortrait.userInteractionEnabled = YES;
                    [self addTapGestureRecognizerOnImageView:loginCell.imageHeadPortrait];
                }else{
                    NSLog(@"%@",error);
                }
            }];
        }else{
            loginCell.imageHeadPortrait.image = [UIImage imageNamed:@"UserCenter_HeadPortrait"];
        }
        loginCell.labelUserName.text = [object[@"localData"] objectForKey:@"userName"];
    }];
    
}

- (void)addTapGestureRecognizerOnImageView:(UIImageView *)imageHeadPortrait
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    self.userIcon = imageHeadPortrait;
    [self.userIcon addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer *)sender
{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
    pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:pickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    self.userIcon.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    HelperModifyUserIconSize *helper = [[HelperModifyUserIconSize alloc] init];
    self.userIcon.image = [helper modifyUserHeaderPortraitSize:self.userIcon.image WithImageWidth:self.userIcon.image.size.width * 0.3 imageHeight:self.userIcon.image.size.height * 0.3];
    NSData *dataImage = UIImagePNGRepresentation(self.userIcon.image);
    AVFile *fileImage = [AVFile fileWithData:dataImage];
    [self.userObject setObject:fileImage forKey:@"userImage"];
    [self.userObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addLogoutCellOnCell:(GKZYUserLogoutTableViewCell *)logoutCell
{
    logoutCell.imageHeadPortrait.image = [UIImage imageNamed:@"UserCenter_HeadPortrait"];
    [logoutCell.buttonLogin addTarget:self action:@selector(buttonLoginAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //修改资料
    if (indexPath.row == 1) {
        if ([AVUser currentUser]) {
            GKZYModifyUserInformationViewController *modifyVC = [[GKZYModifyUserInformationViewController alloc] init];
            modifyVC.userImageBlock = ^(UIImage *image)
            {
                self.userIcon.image = image;
            };
            modifyVC.userObjectId = self.userObjectId;
            [self.navigationController pushViewController:modifyVC animated:YES];
        }else{
            GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }
    }
    //重置密码
    if (indexPath.row == 2) {
        if ([AVUser currentUser]) {
            GKZYUserResetPasswordViewController *resetPasswordVC = [[GKZYUserResetPasswordViewController alloc] init];
            [self.navigationController pushViewController:resetPasswordVC animated:YES];
        }else{
            GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }
    }
    
    //关于我们
    if (indexPath.row == 4) {
        GKZYAboutUsViewController *aboutUsVC = [[GKZYAboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutUsVC animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (void)buttonLoginAction:(UIButton *)sender
{
    GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
    loginVC.weChatUserMessageBlock = ^(NSMutableDictionary *dicMessage)
    {
#warning 单例
        [UserMessageShare sharedUserMessage].currentWeChatUserName = dicMessage[@"userName"];
        [UserMessageShare sharedUserMessage].currentWeChatUserIcon = dicMessage[@"userIcon"];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)rightBarButtonAction:(UIBarButtonItem *)sender
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定注销?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertActionSure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.rightBarButton setTitle:@""];
        [AVUser logOut];
        [UserMessageShare sharedUserMessage].currentWeChatUserName = nil;
        [UserMessageShare sharedUserMessage].currentWeChatUserIcon = nil;
        [UserMessageShare sharedUserMessage].currentUserName = nil;
        [UserMessageShare sharedUserMessage].currentUserImage = nil;
        [self.tableViewList reloadData];
    }];
    UIAlertAction *alertActionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:alertActionSure];
    [alertController addAction:alertActionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0) {
        return self.view.frame.size.height * 0.08;
    }else if(indexPath.row == 0){
        return self.view.frame.size.height * 0.28;
    }
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
